package com.welkom.everydate.web;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.welkom.everydate.services.interfaces.RoleService;
import com.welkom.everydate.services.interfaces.UserService;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.welkom.everydate.common.Constants;
import com.welkom.everydate.domain.Role;
import com.welkom.everydate.domain.User;
import com.welkom.everydate.util.MessageReader;
import com.welkom.everydate.util.web.Operation;
import com.welkom.everydate.util.web.PageData;
import com.welkom.everydate.util.web.PageHeaderAnnotationResolver;
import com.welkom.everydate.util.web.RequestResult;
@Controller
public class UserManagement {
	@Resource
	UserService userService;
	
	@Resource
	RoleService roleService;
	
	@RequestMapping("/userManagement.html")
	public String userManagement(Model model){
		return "common/userManagement/index";
	}
	@RequestMapping("/userQuery.html")
	@ResponseBody
	public PageData<User> getUsersByPage(@RequestParam(required=true,value="userJsonString") String userJsonString,@RequestParam(required=true,value="pageNum") int pageNum,@RequestParam(required=true,value="pageSize")int pageSize){
		JSONArray array = JSONArray.fromObject(userJsonString);//先读取串数组
		 Object[] objectArray = array.toArray();  
		 while(objectArray[0] instanceof JSONArray){
			 JSONArray currentArray=(JSONArray)objectArray[0];
			 Object[] currentObjectArray=currentArray.toArray();
			 objectArray=currentObjectArray;
		 }
		 if(pageSize==0){
				pageSize=Constants.Pagination.DEFAULT_PAGE_SIZE;
		 }
		 if(pageNum==0){
			 pageNum=1;
		 }
		 JSONObject obj = JSONObject.fromObject(objectArray[0]);
		 User user=(User)obj.toBean(obj,User.class);
		 int totalCount=userService.getUserTotalCountByCondition(user);
		 PageData<User> pageData=new PageData<User>();
		 pageData.setCurrentPage(pageNum);
		 pageData.setCurrentPageSize(pageSize);
		 pageData.setTotalCount(totalCount);
		 if(pageData.getPageNavigatorLength()==0){
			 pageData.setPageNavigatorLength(Constants.Pagination.DEFAULT_PAGE_NAVIGATOR_LENGTH);
		 }
		 pageData.setPageHeaders(PageHeaderAnnotationResolver.getHeadersFromDomain(User.class));
		 List<Operation> operations=new ArrayList<Operation>();
		 pageData.setOperations(operations);
		 List<User> users=userService.queryUserByPage(user, pageData.getStartIndex(), pageSize);
		 pageData.setData(users);
		 return pageData;
	}
	
	@RequestMapping("/getAllUsers.html")
	@ResponseBody
	public List<User> getAllUsers(){
		 List<User> users=userService.getAllUsers(); 
		 return users;
	}
	
	@RequestMapping("/getUserDetail.html")
	@ResponseBody
	public RequestResult<User> getUserDetail(@RequestParam(required=true,value="userId")long userId){
		RequestResult<User> result=new RequestResult<User>();
		User user= userService.getUserByUserId(userId);
		if(user==null){
			result.setResultCode(Constants.ResultCode.RESULT_CODE_FAIL);
			result.setReason(MessageReader.getMessage(Constants.Message.MESSAGE_OBJECT_NOT_EXSIT));
		}else{
			 result.setResultCode(Constants.ResultCode.RESULT_CODE_SUCCESS);
			 result.setData(user);
		}
		return result;
	}
	
	@RequestMapping("/saveChangesToUser.html")
	@ResponseBody
	public RequestResult<User> saveChangesToUser(@RequestParam(required=true,value="userJsonString") String userJsonString){
		JSONArray array = JSONArray.fromObject(userJsonString);//先读取串数组
		 Object[] objectArray = array.toArray();  
		 while(objectArray[0] instanceof JSONArray){
			 JSONArray currentArray=(JSONArray)objectArray[0];
			 Object[] currentObjectArray=currentArray.toArray();
			 objectArray=currentObjectArray;
		 }
		 JSONObject obj = JSONObject.fromObject(objectArray[0]);
		 User user=(User)obj.toBean(obj, User.class);
		 userService.updateUser(user);
		 RequestResult<User> result=new RequestResult<User>();
		 result.setResultCode(Constants.ResultCode.RESULT_CODE_SUCCESS);
		 result.setData(user);
		 return result;
	}
	
	@RequestMapping("/addUser.html")
	@ResponseBody
	public RequestResult<User> addUser(@RequestParam(required=true,value="userJsonString") String userJsonString){
		JSONArray array = JSONArray.fromObject(userJsonString);//先读取串数组
		 Object[] objectArray = array.toArray();  
		 while(objectArray[0] instanceof JSONArray){
			 JSONArray currentArray=(JSONArray)objectArray[0];
			 Object[] currentObjectArray=currentArray.toArray();
			 objectArray=currentObjectArray;
		 }
		 JSONObject obj = JSONObject.fromObject(objectArray[0]);
		 User user=(User)obj.toBean(obj, User.class);
		 userService.addUser(user);
		 RequestResult<User> result=new RequestResult<User>();
		 result.setResultCode(Constants.ResultCode.RESULT_CODE_SUCCESS);
		 result.setData(user);
		 return result;
	}
	
	@RequestMapping("/removeUserById.html")
	@ResponseBody
	public RequestResult<User> removeUserById(@RequestParam(required=true,value="userId")long userId){
		userService.deleteUser(userId);
		RequestResult<User> result=new RequestResult<User>();
		result.setResultCode(Constants.ResultCode.RESULT_CODE_SUCCESS);
		return result;
	}
	@RequestMapping("/getCurrentUserRoles.html")
	@ResponseBody
	public RequestResult<Map> loadUserRolesByUserId(@RequestParam(required=true,value="userId")long userId){
		Map<String,Object> data=new HashMap<String,Object>();
		List<Role> currentRoles=roleService.getRolesByUserId(userId);
		List<Role> allRoles=roleService.getAllRoles();
		List<Role> otherRoles=new ArrayList<Role>();
		for(Role role:allRoles){
			if(!currentRoles.contains(role)){
				otherRoles.add(role);
			}
		}
		
		data.put("currentRoles", currentRoles);
		data.put("otherRoles", otherRoles);
		RequestResult<Map> result=new RequestResult<Map>();
		result.setResultCode(Constants.ResultCode.RESULT_CODE_SUCCESS);
		result.setData(data);
		return result;
	}
	
	@RequestMapping("/saveRoleChangesToUser.html")
	@ResponseBody
	public RequestResult<User> sangeRoleChangesToUser(@RequestParam(required=true,value="roleJsonString") String roleJsonString,@RequestParam(required=true,value="userId")long userId){
		JSONArray array = JSONArray.fromObject(roleJsonString);//先读取串数组
		Object[] objectArray = array.toArray();  
		List<Role> roles=new ArrayList<Role>();
		for(int i=0;i<objectArray.length;i++){
			JSONObject obj = JSONObject.fromObject(objectArray[i]);
			Role role=(Role)obj.toBean(obj, Role.class);
			roles.add(role);
		}
		roleService.removeRolesByUserId(userId);
		roleService.addRolesToUser(roles, userId);
		RequestResult<User> result=new RequestResult<User>();
		result.setResultCode(Constants.ResultCode.RESULT_CODE_SUCCESS);
		return result;
	}
	

}
